package com.mpgame.common.manager;

import com.mpgame.common.handler.BaseHandler;
import com.mpgame.common.handler.HeartbeatHandler;
import com.mpgame.common.utils.Log;
import com.mpgame.common.proto.*;

import io.netty.channel.ChannelHandlerContext;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class HandlerMgr {
    private final Map<CmdId, BaseHandler> handlers = new ConcurrentHashMap<>();

    public HandlerMgr(){
        initBasicHandlers();
    }

    private void initBasicHandlers(){
        HeartbeatHandler hbh = new HeartbeatHandler();
        registHandler(CmdId.HEARTBEAT_REQ, hbh);
        registHandler(CmdId.HEARTBEAT_RSP, hbh);
    }

    public void handle(ChannelHandlerContext ctx, GamePacket pkt){
        CmdId cmdId = pkt.getCmd();
        BaseHandler handler = handlers.get(cmdId);

        if(handler == null){
            Log.warn("命令" + cmdId + "的处理未注册！");
            return;
        }

        if(!handler.isEnabled()){
            Log.debug("处理器" + cmdId + "已禁用！");
            return;
        }

        try{
            // 处理成功
            if(handler.handle(ctx, pkt)){
                Log.debug("消息" + cmdId + "处理成功！");
            }
            else{
                Log.warn("消息" + cmdId + "处理失败！");
            }
        }
        catch(Exception e){
            Log.err("处理器" + cmdId + "处理异常：" + e.getMessage());
            return;
        }
    }

    public HandlerMgr registHandler(CmdId cmdId, BaseHandler handler){
        if(handlers.containsKey(cmdId)){
            Log.warn("相同的" + cmdId + "处理器已存在，注册处理器失败！");
            return this;
        }
        handlers.put(cmdId, handler);
        Log.info("成功注册" + cmdId + "的处理器！");
        return this;
    }

    public void removeHandler(CmdId cmdId){
        if(handlers.remove(cmdId) != null){
            Log.info("成功移除命令" + cmdId + "的处理器！");
        }
        else{
            Log.warn("移除失败：命令" + cmdId + "的处理器不存在！");
        }
    }

    public void clearAll(){
        handlers.clear();
        Log.info("已清空所有处理器");
    }
}
